package com.inspector.app.ui.main

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.multidex.BuildConfig
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.inspector.app.BaseApp

import com.inspector.app.R
import com.inspector.app.databinding.ActivityMainBinding
import com.inspector.app.di.location.LocationService
import com.inspector.app.di.upversion.VersionModel
import com.inspector.app.di.util.UI
import com.inspector.app.di.util.UI.makeStatusBarTransparent
import com.inspector.app.di.vo.event.EventLocationChanged
import com.inspector.app.ui.base.BaseDJActivity
import com.inspector.app.util.ConvertHelper
import com.inspector.app.util.LogUtil
import com.permissionx.guolindev.PermissionX
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : BaseDJActivity() {

    @Inject
    lateinit var application: BaseApp

    private var wakeLock: PowerManager.WakeLock? = null
    private val powerManager: PowerManager by lazy {
        getSystemService(Context.POWER_SERVICE) as PowerManager
    }

    private lateinit var binding: ActivityMainBinding
    private var permissions = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.WRITE_SETTINGS,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_STATE
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        UI.registerEvents(this)
        requestPermission()
        initDatas()
    }

    private fun setupView() {
        val navView: BottomNavigationView = binding.navView
        val navController = findNavController(R.id.nav_host_fragment_activity_main)
        val mainNavigationGraph = navController.navInflater.inflate(R.navigation.mobile_navigation)
        mainNavigationGraph.setStartDestination(R.id.navigation_home)
        navController.graph = mainNavigationGraph
        navView.setupWithNavController(navController)

        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            val darkFontModel = destination.id != R.id.navigation_task
            makeStatusBarTransparent(darkFontModel)
        }

        //[开启前台定位通知]
        startForegroundService()
    }

    private var isServiceRunning: Boolean = false
    private fun startForegroundService() {
        val running = ConvertHelper.isServiceRunning(this, LocationService::class.java.name)
        if (running || isServiceRunning) return
        val intent = Intent(applicationContext, LocationService::class.java)
        ContextCompat.startForegroundService(applicationContext, intent)
        isServiceRunning = true
    }

    private fun stopForegroundService() {
        val running = ConvertHelper.isServiceRunning(this, LocationService::class.java.name)
        if (!running || !isServiceRunning) return
        val intent = Intent(applicationContext, LocationService::class.java)
        stopService(intent)
        isServiceRunning = false
    }


    @Suppress("UNUSED_ANONYMOUS_PARAMETER")
    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            permissions += arrayOf(Manifest.permission.FOREGROUND_SERVICE)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissions += arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        }
        permissions += if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        }
        //[https://developer.android.com/about/versions/14/changes/fgs-types-required?hl=zh-cn#data-sync]
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissions += arrayOf(
                Manifest.permission.FOREGROUND_SERVICE_LOCATION,
                Manifest.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE,
                Manifest.permission.FOREGROUND_SERVICE_DATA_SYNC
            )
        }

        PermissionX.init(this).permissions(*permissions)
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(deniedList, "使用App需要进行授权", "授权", "取消")
            }
            .onForwardToSettings { scope, deniedList ->
                scope.showForwardToSettingsDialog(
                    deniedList, "您需要在“设置”中手动授予必要的权限", "前往", "取消"
                )
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    setupView()
                } else {
                    UI.displayTopSnackBar(this, binding.container, "使用App需要进行授权")
                    forceStopApp()
                }
            }
    }

    private fun initDatas() {
        //版本更新
        if (!BuildConfig.DEBUG) {
            /**检查版本更新*/
            val versionViewModel = ViewModelProvider(this)[VersionModel::class.java]
            versionViewModel.isUpgrade(this)
        }
    }

    private fun forceStopApp() {
        Thread {
            try {
                Thread.sleep(3000)
            } catch (ignored: Exception) {
            }
            finish()
        }.start()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLocationChanged(event: EventLocationChanged) {
        LogUtil.e("地图界面", "EventLocationChanged")
    }

    @SuppressLint("WakelockTimeout", "Wakelock")
    private fun acquireWakeLock() {
        try {
            if (wakeLock == null) {
                wakeLock = powerManager.newWakeLock(
                    PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ON_AFTER_RELEASE,
                    javaClass.canonicalName
                )
                wakeLock?.acquire()
                wakeLock?.release()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun releaseWakeLock() {
        try {
            if (wakeLock?.isHeld == true) {
                wakeLock?.release()
                wakeLock = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        UI.unregisterEvents(this)
        stopForegroundService()
        releaseWakeLock()
    }


}